package com.derbysoft.defender.controller;

import com.derbysoft.defender.api.requester.AccessTokenRequester;
import com.derbysoft.defender.api.response.OAuth2AccessToken;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>some description here.</p>
 * Created by Afee Lee on 2017-03-27 08:26
 *
 * @author Afee Lee
 * @version 1.0
 * @see Object
 * @since 1.8
 */
@RestController
@RequestMapping("/auth")
public class AuthController extends AbstractController {
    protected String clientId = "myClientId";
    protected String clientSecret = "myClientSecret";

    private static final String URL_TOKEN_FOR_AUTH_CODE = "/oauth/token?grant_type=authorization_code&redirect_uri=//localhost:8882/defender/auth/code&code=";
    private static final String URL_TOKEN_FOR_PASSWORD = "/oauth/token?grant_type=password&username=%s&password=%s";

    @RequestMapping("/code")
    public Object handleAuthCode(String code) {
        return new AccessTokenRequester(clientId, clientSecret)
                .request(authUrlPrefix + URL_TOKEN_FOR_AUTH_CODE + code);
    }

    @RequestMapping("/implicit")
    public Object handleImplicit(String access_token) {
        //how to get param after # of an url???
        return access_token;
    }

    //URL not end with .html: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
    @PostMapping(value = "/password", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public OAuth2AccessToken handlePassword(String username, String password) {
        return new AccessTokenRequester(clientId, clientSecret)
                .request(authUrlPrefix + String.format(URL_TOKEN_FOR_PASSWORD, username, password));
    }
}
